import functools

import requests
from pex import toml

from logger import logger

CFG = toml.load('config.toml')

TYPE_FILE = "files"
TYPE_REVIEW = "review"
TYPE_COMMENTS = "comments"

LOGGER = logger.CustomLogger()

def skip_if_debug(func):
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        if hasattr(self, 'debug_mode') and self.debug_mode:
            LOGGER.debug(f"func {func} not executed, args: {args}")
            return requests.Response()
        return func(self, *args, **kwargs)
    return wrapper

class GitClient:
    def __init__(self, debug_mode=False, owner="", name=""):
        self.debug_mode = debug_mode
        url_prefix = CFG.get("repo", {}).get("url_prefix")
        self.url_prefix = f"{url_prefix}/{owner}/{name}/pulls"

    def get_url(self, pr_number, type):
        return f"{self.url_prefix}/{pr_number}/{type}"

    def get_files(self, pr_number, params):
        url = self.get_url(pr_number, TYPE_FILE)
        response = requests.get(url, params=params)
        if response.status_code == 200:
            return response.json()
        else:
            LOGGER.error(f"[{pr_number}] get {url} failed, code {response.status_code}, reason {response.reason}")
        return []

    def get_filenames(self, pr_number, params):
        url = self.get_url(pr_number, TYPE_FILE)
        response = requests.get(url, params=params)
        files = []
        if response.status_code == 200:
            res = response.json()
            for f in res:
                files.append(f['filename'])
        else:
            raise Exception(f"code {response.status_code}, reason {response.reason}")
        return files

    def get_comments(self, pr_number, params):
        url = self.get_url(pr_number, TYPE_COMMENTS)
        response = requests.get(url, params=params)
        if response.status_code == 200:
            return response.json()
        else:
            raise Exception(f"code {response.status_code}, reason {response.reason}")

    def get_pr(self, pr_number, params):
        url = f"{self.url_prefix}/{pr_number}"
        return requests.get(url, params=params)

    @skip_if_debug
    def review(self, pr_number, headers):
        url = self.get_url(pr_number, TYPE_REVIEW)
        return requests.post(url, headers=headers)

    @skip_if_debug
    def comment(self, pr_number, headers, json):
        url = self.get_url(pr_number, TYPE_COMMENTS)
        return requests.post(url, headers=headers, json=json)
